package meijuli.com.join51.business.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.CertificationActivity;
import meijuli.com.join51.business.aliyun.ImageUtils;
import com.jhx.common.model.User;
import meijuli.com.join51.business.ui.widget.ClearEditText;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.ToastUtil;
import com.jhx.common.utils.UserManager;

/**
 * 身份认证页面
 *
 * @author wenqin 2017-04-14 14:17
 */
public class AttestPersonFragment extends PhotoFragment implements ImageUtils.SelectImageListener {
    private View view;
    private String regex = "^[\\u4e00-\\u9fa5]+$";
    private String idRegex = "^[0-9a-zA-Z]{1,18}$";
    Button mNextBtn;
    ClearEditText mEditTop;
    ClearEditText mEditBottom;
    ImageView mTakePhonePositive;
    ImageView mTakePhoneNegative;
    Button mPreviousBtn;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_attest_person, container, false);
        }
        mNextBtn = view.findViewById(R.id.next_btn);
        mEditTop = view.findViewById(R.id.edit_name);
        mEditBottom = view.findViewById(R.id.edit_num);
        mTakePhonePositive = view.findViewById(R.id.take_phone_positive);
        mTakePhoneNegative = view.findViewById(R.id.take_phone_negative);
        mPreviousBtn = view.findViewById(R.id.previous_btn);
        mNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nextBtnClick();
            }
        });
        mPreviousBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onPreviousBtnClick();
            }
        });
        mTakePhonePositive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onPhotoPic1Click();
            }
        });
        mTakePhoneNegative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onPhotoPick2Click();
            }
        });
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((CertificationActivity)getActivity()).setToolbarTitle("法人信息");
        initView();
        initData();
    }

    private void initView() {

    }

    private void initData() {

        if (UserManager.get().checkUserNull(getActivity())) {
            return;
        }
        User userInfo = UserManager.get().getUser();

        if (userInfo != null &&
                !TextUtils.isEmpty(userInfo.getLocalIDback()) &&
                !TextUtils.isEmpty(userInfo.getLocalIDfront())) {
            mEditTop.setText(userInfo.getLegal());
            mEditBottom.setText(userInfo.getIDCard());
            Glide.with(this).load(userInfo.getLocalIDback())
                    .error(R.mipmap.add_pic)
                    .into(mTakePhoneNegative);
            Glide.with(this).load(userInfo.getLocalIDfront())
                    .error(R.mipmap.add_pic)
                    .into(mTakePhonePositive);

            mPicPath1 = userInfo.getLegalIDfront();
            mPicPath2 = userInfo.getLegalIDback();
            mLocalPicPath1 = userInfo.getLocalIDfront();
            mLocalPicPath2 = userInfo.getLocalIDback();

            SoftInputUtil.get().hideSoftKeyboard(getActivity());
        }
    }

    @Override
    protected void onUpLoadSuccess(String cloudKey, String sourceFilePath) {
        if (toType == 1) {
            Glide.with(this).load(sourceFilePath).error(R.mipmap.img_default).into(mTakePhonePositive);
        } else if (toType == 2) {
            Glide.with(this).load(sourceFilePath).error(R.mipmap.img_default).into(mTakePhoneNegative);
        }
    }

    void onPhotoPick2Click() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        toType = 2;
        showListDialog();
    }

    void onPhotoPic1Click() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        toType = 1;
        showListDialog();
    }

    void onPreviousBtnClick() {
        getActivity().onBackPressed();
    }

    void nextBtnClick() {
        SoftInputUtil.get().hideSoftKeyboard(getActivity());
        if (TextUtils.isEmpty(mEditTop.getText()) || TextUtils.isEmpty(mEditBottom.getText())) {
            ToastUtil.getInstance().showToast(getActivity(), "法人信息不能为空");
            return;
        } else if(mEditTop.getText().length() < 2 || mEditTop.getText().length() > 16) {
            ToastUtil.getInstance().showToast(getActivity(), "法人姓名只能是2位到16位字符之间");
            return;
        } else if(!checkInput(mEditTop.getText().toString(), regex)) {
            ToastUtil.getInstance().showToast(getActivity(), "法人姓名只能输入中文");
            return;
        }

        if (TextUtils.isEmpty(mLocalPicPath2) || TextUtils.isEmpty(mLocalPicPath1)) {
            ToastUtil.getInstance().showToast(getActivity(), "照片不能为空");
            return;
        }

        if (TextUtils.isEmpty(mPicPath2) || TextUtils.isEmpty(mPicPath1)) {
            ToastUtil.getInstance().showToast(getActivity(), "图片上传失败，请重试");
            return;
        }

        String idNumber = mEditBottom.getText().toString();
        if (TextUtils.isEmpty(idNumber)) {
            ToastUtil.getInstance().showToast(getActivity(), "身份证号码不能为空");
            return;
        } else if(!checkInput(idNumber, idRegex)) {
            ToastUtil.getInstance().showToast(getActivity(), "身份证号码只能包含数字和字母,并且只能18位以内");
            return;
        }

        UserManager.get()
                .setLegalIDfront(mPicPath1)
                .setLegalIDback(mPicPath2)
                .setLocalIDback(mLocalPicPath2)
                .setLocalIDfront(mLocalPicPath1)
                .setLegal(mEditTop.getText().toString())
                .setIDCard(mEditBottom.getText().toString());

        switchFragment(this, new AttestShopFragment());
    }

    /**
     * 检测输入
     * 只允许字母、数字和汉字
     */
    private Boolean checkInput(String str, String regex) {
        Pattern pat = Pattern.compile(regex);
        Matcher mat = pat.matcher(str);
        return mat.matches();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ((CertificationActivity)getActivity()).setToolbarTitle("法人信息");
    }

}
